package com.crawling.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.crawling.mapper.TAttachMapper;
import com.crawling.mapper.TContentsMapper;
import com.crawling.mapper.TMetasMapper;
import com.crawling.mapper.TRelationshipsMapper;
import com.crawling.model.*;
import com.crawling.service.CreatePhotoService;
import com.crawling.util.HttpClientUtil;
import com.crawling.util.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.io.ByteArrayInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CreatePhotoServiceImpl implements CreatePhotoService {

    @Autowired
    TContentsMapper tContentsMapper;
    @Autowired
    TMetasMapper tMetasMapper;
    @Autowired
    TRelationshipsMapper relationshipsMapper;
    @Autowired
    TAttachMapper tAttachMapper;
    public static String fileUrl = "/api/attach/view";

    public static String fileUrlHost = "http://localhost:8080";
    IdWorker idWorker = new IdWorker(1, 1);

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Async
    public void createPhoto(CrawlingPicThumbnail crawlingPicThumbnail, List<CrawlingBigPic> bigPics, List<CrawlingPicTags> crawlingPicTags) {
        if (CollectionUtil.isEmpty(bigPics) || CollectionUtil.isEmpty(crawlingPicTags)) {
            return;
        }
        TContents tContents = new TContents();
        tContents.setTitle(bigPics.get(0).getBigPicText());
        tContents.setCreated((int) (System.currentTimeMillis() / 1000L));
        tContents.setModified(0);
        //![]()
        //![](http://127.0.0.1:8080/files/1/20200306/5f9966fa-69af-4707-893e-961ec95f8797.jpg)
        //![](http://127.0.0.1:8080/files/1/20200306/74b2173f-9f82-43c2-9d2a-7718baf1a358.jpg)
        //![](http://127.0.0.1:8080/files/1/20200306/10d12469-dfcd-45e8-a561-d3d53e217438.jpg)
        StringBuilder builder = new StringBuilder();
        boolean hastime = false;
        for (CrawlingBigPic bigPic : bigPics) {

            //插入到附件表中
            TAttach tAttach = new TAttach();
            tAttach.setAuthorid(1);
            tAttach.setCreated(tContents.getCreated());
            tAttach.setFtype("image");
            long id = idWorker.nextId();
            String name = StringUtils.substringAfterLast(bigPic.getBigPicHref(), "/");
            tAttach.setFkey(fileUrl + "/" + id + "/" + name);
            tAttach.setWebUrl(bigPic.getBigPicHref());
            try {
                tAttach.setHash(getFileMD5(HttpClientUtil.downloadFileByte(bigPic.getBigPicHref())));
            } catch (Exception e) {
                e.printStackTrace();
            }
            tAttach.setFname(name);
            // 更新创建时间
            if (!hastime && name.length() > 8) {
                String timeimg = name.substring(0, 8);
                tContents.setCreated(Integer.parseInt((DateUtil.parse(timeimg, "yyyyMMdd").getTime() / 1000L) + ""));
                hastime = true;
            }
            Example exampletAttach = new Example(TAttach.class);
            exampletAttach.createCriteria().andEqualTo("webUrl", tAttach.getWebUrl());
            List<TAttach> exampletAttachList = tAttachMapper.selectByExample(exampletAttach);
            if (CollectionUtil.isEmpty(exampletAttachList)) {
                tAttachMapper.insertSelective(tAttach);
            } else {
                tAttach = exampletAttachList.get(0);
            }
            String textUrl = null;
            try {
                textUrl = bigPic.getBigPicHref().startsWith("https") ? tAttach.getFkey() : bigPic.getBigPicHref();
            } catch (Exception e) {
                log.error("拼接content url error", e);
            }
            if (textUrl == null) {
                continue;
            }
            // content 内容拼接
            builder.append("![](");
            builder.append(textUrl);
            builder.append(") ");
        }
        if (StringUtils.isBlank(builder)) {
            return;
        }
        tContents.setContent(builder.toString());
        tContents.setType("photo");
        tContents.setStatus("publish");
        String tag = "";
        for (CrawlingPicTags crawlingPicTag : crawlingPicTags) {
            tag = tag + crawlingPicTag.getTagName() + ",";
        }
        tContents.setTags(tag);
        tContents.setCategories("美女");
        tContents.setAllowcomment(true);

        Example exampleTContents = new Example(TContents.class);
        exampleTContents.createCriteria().andEqualTo("title", tContents.getTitle());
        List<TContents> exampleTContentsList = tContentsMapper.selectByExample(exampleTContents);
        if (CollectionUtil.isEmpty(exampleTContentsList)) {
            tContentsMapper.insertSelective(tContents);
        } else {
            tContents = exampleTContentsList.get(0);
        }

        List<TMetas> tMetasList = new ArrayList<>();
        for (CrawlingPicTags crawlingPicTag : crawlingPicTags) {
            TMetas tMetas = new TMetas();
            tMetas.setName(crawlingPicTag.getTagName());
            tMetas.setSlug(crawlingPicTag.getTagName());
            tMetas.setType("tag");
            tMetas.setSort(0);
            if ("y".equals(crawlingPicTag.getIsPeople())) {
                tMetas.setSort(666666);
            }
            //保存
            Example example = new Example(TMetas.class);
            example.createCriteria().andEqualTo("name", tMetas.getName()).andEqualTo("type", tMetas.getType());
            List<TMetas> tMetas1s = tMetasMapper.selectByExample(example);
            if (CollectionUtil.isEmpty(tMetas1s)) {
                tMetasMapper.insertSelective(tMetas);
            } else {
                tMetas = tMetas1s.get(0);
            }
            tMetasList.add(tMetas);
        }
        TRelationships relationships = new TRelationships();
        for (TMetas tMetas : tMetasList) {
            relationships.setCid(tContents.getCid());
            relationships.setMid(tMetas.getMid());
            try {
                relationshipsMapper.insertSelective(relationships);
            } catch (Exception e) {
                log.error("关联关系保存失败", e);
            }
        }

    }


    public static String getFileMD5(byte[] buf) {
        BigInteger bigInt = null;
        try {
            ByteArrayInputStream fis = new ByteArrayInputStream(buf);
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = fis.read(buffer, 0, 1024)) != -1) {
                md.update(buffer, 0, length);
            }
            bigInt = new BigInteger(1, md.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return bigInt.toString(16);
    }

    public static void main(String[] args) {
        String name = "20200313041205266.jpg";
        String timeimg = name.substring(0, 8);
        System.out.println();
        ;
    }
}
